<template>
  <el-container>
    <el-aside style="min-width:200px; min-height:600px;">
      <!-- <el-scrollbar> -->
      <el-tree
        ref="labelTree"
        :data="labelTree"
        :props="defaultProps"
        node-key="id"
        highlight-current
        empty-text="No data"
        default-expand-all
        @node-click="handleNodeClick"
      >
        <span slot-scope="{ node, data }">
          <span :title="node.label">{{ node.label }}</span>
        </span>
      </el-tree>
      <!-- </el-scrollbar> -->
    </el-aside>
    <el-main>
      <div class="panel-border">
        <SearchForm
          ref="mychild"
          size="mini"
          :search-data="searchData"
          :search-form="searchForm"
          :search-handle="searchHandle"
        />
      </div>
      <div class="panel-border">
        <el-row>
          <avue-crud
            ref="crud"
            :option="option"
            :data="optionData"
            :table-loading="loading"
            @on-load="initData"
            @refresh-change="refreshChange"
          >
            <template slot="statusCd" slot-scope="scope">
              <span
                v-for="item in labelStatusCd"
                v-if="item.item_code == scope.row.statusCd"
                :label="item.item_code"
              >{{ item.item_text }}</span>
            </template>
            <template slot="menuRight" slot-scope="scope">
              <!--<el-button type="primary"-->
              <!--icon="el-icon-plus"-->
              <!--size="mini"-->
              <!--plain-->
              <!--@click="dialogTitle=$t('add');modelType='add';showAddModel=true"-->
              <!--v-text="$t('modelMining.add')">-->
              <!--</el-button>-->
              <button class="customize-add" @click="dialogTitle=$t('add');modelType='add';showAddModel=true">
                <img src="../../images/add.png">
                {{ $t('add') }}
              </button>
            </template>
            <template slot="option" slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.statusCd == 1200 || scope.row.statusCd == 1500 ? false : true"
                @click="dialogTitle=$t('labelSpec.editModel');labelId=scope.row.labelId;modelType='edit';showAddModel=true"
                v-text="$t('edit')"
              />
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.statusCd == 1200 || scope.row.statusCd == 1500 || scope.row.statusCd == 1400 || scope.row.statusCd == 1600 ? false : true"
                @click.stop="editStatus(scope.row.labelId , 1100)"
                v-text="$t('delete')"
              />
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.statusCd == 1200 || scope.row.statusCd == 1500 ? false : true"
                @click="dialogTitle=$t('labelSpec.submitAudit');labelId=scope.row.labelId;modelType='submitAudit';showDetailModel=true"
                v-text="$t('labelSpec.submitAudit')"
              />
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.statusCd == 1400 || scope.row.statusCd == 1600 ? false : true"
                @click.stop="editStatus(scope.row.labelId , 1000)"
                v-text="$t('online')"
              />
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.statusCd == 1000 ? false : true"
                @click.stop="editStatus(scope.row.labelId , 1600)"
                v-text="$t('offline')"
              />
            </template>
            <template slot="labelName" slot-scope="scope">
              <p style="color: #4284D7;" @click="dialogTitle=$t('labelSpec.detail');labelId=scope.row.labelId;modelType='detail';showDetailModel=true">{{ scope.row.labelName }}</p>
            </template>
            <template slot="empty">
              {{ $t('empty') }}
            </template>
          </avue-crud>
          <!--分页-->
          <pagination :page="page" />
        </el-row>
      </div>
    </el-main>

    <!-- 标签规格详情 -->
    <el-dialog
      :visible.sync="showDetailModel"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <specDetail
        :key="new Date().getTime()"
        :model-type="modelType"
        :label-id="labelId"
        :dialog-options="dialogOptions"
        :label-object="labelObject"
        :label-update-frequency="labelUpdateFrequency"
        :label-datas-source="labelDatasSource"
        :label-value-type="labelValueType"
        :label-data-type="labelDataType"
        :label-status-cd="labelStatusCd"
        @onDetailSuccess="onDetailSuccess"
      />
    </el-dialog>

    <!-- 标签规格新增 -->
    <el-dialog
      ref="addSpec"
      top="10vh"
      :visible.sync="showAddModel"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <specAdd
        :key="new Date().getTime()"
        :model-type="modelType"
        :label-id="labelId"
        :label-object="labelObject"
        :label-update-frequency="labelUpdateFrequency"
        :label-datas-source="labelDatasSource"
        :label-value-type="labelValueType"
        :label-data-type="labelDataType"
        :dialog-options="dialogOptions"
        @onAddSuccess="onAddSuccess"
      />
    </el-dialog>
  </el-container>
</template>

<script>
import SearchForm from '../../components/search-filter/searchForm'
import specDetail from './specDetail'
import specAdd from './specAdd'
import pagination from '../../components/pagination/pagination'

export default {
  name: 'Spec',
  components: {
    SearchForm,
    specDetail,
    specAdd,
    pagination
  },
  data() {
	  return {
      loading: true,
      dialogTitle: '',
      labelObject: [],
      labelUpdateFrequency: [],
      labelStatusCd: [],
      labelDatasSource: [],
      labelValueType: [],
      labelDataType: [],
      // 查询表单
      searchData: {
        labelObject: '',
        labelUpdateFrequency: '',
        statusCd: '',
        labelName: '',
        labelLevelId: 1
      },
      searchForm: [
		  { type: 'Select', label: '标签对象:', search: 'labelSpec.listTable.labelObject', prop: 'labelObject', datas: [] },
		  { type: 'Select', label: '更新频率:', search: 'labelSpec.listTable.labelUpdateFrequency', prop: 'labelUpdateFrequency', datas: [] },
		  { type: 'Select', label: '标签状态:', search: 'labelSpec.listTable.statusCd', prop: 'statusCd', datas: [] },
		  { type: 'Input', label: '模糊检索:', search: 'labelSpec.fuzzySearch', prop: 'labelName', placeholder: '请输入标签编码/名称模糊检索', placeholderFiled: 'labelSpec.placeholder.nameCodeFuzzySearch' }
      ],
      searchHandle: [
		  { label: '查询', search: 'query', type: 'primary', handle: () => this.onSearch() },
		  { label: '重置', search: 'reset', type: 'primary', handle: () => this.onReset() }
      ],
      labelId: 0,
      modelType: 'add',
      showDetailModel: false,
      showAddModel: false,
      labelTree: [],
      defaultProps: {
		  children: 'children',
		  label: 'labelLevelName'
      },
      optionData: [
      ],
      option: {
        index: true,
        indexLabel: this.$t('serialNumber'),
        indexWidth: 100,
        page: false,
        menu: false,
        align: 'center',
        menuAlign: 'center',
        stripe: true,
        border: true,
        column: [
          // {
          // 	label: '序号',
          // 	prop: 'labelId',
          // },
          {
            label: '标签对象',
            prop: 'labelObject',
            minWidth: 100,
            overHidden: true
          }, {
            label: '标签编码',
            prop: 'labelCode',
            minWidth: 100,
            overHidden: true
          }, {
            label: '标签名称',
            prop: 'labelName',
            slot: true,
            minWidth: 100,
            overHidden: true
          }, {
            label: '存储字段',
            prop: 'labelDataCol',
            minWidth: 100,
            overHidden: true
          }, {
            label: '标签状态',
            prop: 'statusCd',
            slot: true,
            minWidth: 100,
            overHidden: true
          },
          // {
          // 	label: '标签时间',
          // 	prop: 'statusDate',
          // 	type:'date',
          // 	format:'yyyy-MM-dd HH:mm:ss',
          // 	minWidth: 100,
          // 	overHidden:true,
          // },{
          // 	label: '更新频率',
          // 	prop: 'labelUpdateFrequency',
          // 	minWidth: 100,
          // 	overHidden:true,
          // },
          {
            label: '创建人',
            prop: 'createStaffName',
            minWidth: 100,
            overHidden: true
          }, {
            label: '操作',
            prop: 'option',
            minWidth: 300,
            slot: true,
            overHidden: true
          }],
        saveBtn: false,
        updateBtn: false,
        cancelBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false
      },
      options: [],
      dialogOptions: [],
      deflutLabelLevelId: 1,
      params: {
        labelLevelId: 1
      },
      page: {
        total: 0,
        limit: 10,
        pageSize: 10,
        pagerCount: 1,
        currentPage: 1,
        pageTo: () => this.getLabelData()
      },
      pageInit: {
        total: 0,
        limit: 10,
        pageSize: 10,
        pagerCount: 1,
        currentPage: 1,
        pageTo: () => this.getLabelData()
      },
      tagData: [],
      reqParams: {}
	  }
  },
  watch: {
	    // 监听语言变化，实时切换表头语言
	    '$i18n.locale': {
	        handler() {
        this.U.changeTableLanguage(this, this.option.column, 'labelSpec.listTable.')
        this.U.changeSearchLanguage(this, this.searchForm, '', 'condition')
        this.U.changeSearchLanguage(this, this.searchForm, '', 'placeholder')
        this.U.changeSearchLanguage(this, this.searchHandle, '', 'btn')
      },
	        immediate: true
	    }
  },
  created() {

  },
  methods: {
    initData() {
      this.getLabelTree()
      this.getLabelData()
      this.getSearchObject()
    },
    getSearchObject() {
      this.labelObject = []
      this.R.forTaglib.getDict('LABEL_OBJECT').then((res) => {
        if (res.ok) {
          for (var i = 0; i < res.length; i++) {
            if (res[i].item_code !== '9000') {
              this.labelObject.push(res[i])
            }
          }
          this.U.setSearchForm(this.searchForm, 'labelObject', this.labelObject)

          this.R.forTaglib.getDict('LABEL_UPDATE_FREQUENCY').then((res) => {
            if (res.ok) {
              this.labelUpdateFrequency = res
              this.U.setSearchForm(this.searchForm, 'labelUpdateFrequency', res)
            }
          })
          this.R.forTaglib.getDict('LABEL_STATUS_CD').then((res) => {
            if (res.ok) {
              this.labelStatusCd = res
              this.U.setSearchForm(this.searchForm, 'statusCd', res)
            }
          })
          this.R.forTaglib.getDict('LABEL_DATA_SOURCE').then((res) => {
            if (res.ok) {
              this.labelDatasSource = res
            }
          })
          this.R.forTaglib.getDict('LABEL_VALUE_TYPE').then((res) => {
            if (res.ok) {
              this.labelValueType = res
            }
          })
          this.R.forTaglib.getDict('LABEL_DATA_TYPE').then((res) => {
            if (res.ok) {
              this.labelDataType = res
            }
          })
        }
      })
    },
    // 搜索
    onSearch() {
      console.log('列表事件onSearch')
      this.params = this.searchData
      this.page = this.pageInit
      this.page.currentPage = 1
      this.page.offset = 1
      this.getLabelData()
    },
    onReset() {
      console.log('重置事件onSearch')
      this.searchData.labelObject = ''
      this.searchData.labelUpdateFrequency = ''
      this.searchData.statusCd = ''
      this.searchData.labelName = ''
      this.page.currentPage = 1
      this.page.offset = 1
      this.params.labelLevelId = 1
      this.$nextTick(() => {
        this.$refs.labelTree.setCurrentKey(this.params.labelLevelId)
      })
      this.getLabelData()
    },
    pageTo(pageIndex, size) {
      this.page.limit = size
      this.page.offset = pageIndex
      this.getLabelData()
    },
    getLabelData() {
      const that = this
      that.loading = true
      this.page.limit = this.page.pageSize
      this.page.offset = this.page.currentPage
      console.log('参数打印：' + this.params)
      const reqParam = this.R.extend(this.params, this.page)
      this.R.forTaglib.postJson('/mktlabel/queryList', reqParam).then(res => {
        if (res.ok) {
          that.page.total = res.rowCount
          that.page.currentPage = res.offset
          that.page.pageSize = res.limit
          that.page.pagerCount = res.pageCount
          that.optionData = res.dataList
          that.loading = false
        }
      })
    },
    getLabelTree() {
      const that = this
      that.loading = true
      this.R.forTaglib.get('/labelLevel/queryList').then(res => {
        this.labelTree = []
        var laberList = res
        // tree
        for (var i = 0; i < laberList.length; i++) {
          if (laberList[i].upLabelLevelId == null) {
            laberList[i].id = laberList[i].labelLevelId
            laberList[i].children = this.getChildren(laberList, laberList[i].labelLevelId)
            this.labelTree.push(laberList[i])
            break
          }
        }
        this.$nextTick(() => {
				    this.$refs.labelTree.setCurrentKey(this.deflutLabelLevelId)
        })
        // options
        this.options = []
        for (var i = 0; i < this.labelTree.length; i++) {
          if (this.labelTree[i].upLabelLevelId == null) {
            // this.labelTree[i].labelLevelPathName=this.labelTree[i].labelLevelName;
            // this.options.push(this.labelTree[i])
            this.getOptions(this.labelTree[i].children, this.labelTree[i])
            break
          }
        }
        // 弹框options
        this.dialogOptions = []
        for (var i = 0; i < this.labelTree.length; i++) {
          if (this.labelTree[i].upLabelLevelId == null) {
            this.labelTree[i].labelLevelPathNameDialog = this.labelTree[i].labelLevelName
            this.dialogOptions.push(this.labelTree[i])
            this.getDialogOptions(this.labelTree[i].children, this.labelTree[i])
            break
          }
        }
        that.loading = false
      }).catch(err => {
        that.$message.error(err.toString())
      })
    },
    getChildren(laberList, labelLevelId) {
      var children = []
      for (var i = 0; i < laberList.length; i++) {
        if (laberList[i].upLabelLevelId != null && laberList[i].upLabelLevelId == labelLevelId) {
          laberList[i].id = laberList[i].labelLevelId
          laberList[i].children = this.getChildren(laberList, laberList[i].labelLevelId)
          children.push(laberList[i])
        }
      }
      return children
    },
    getOptions(labelTree, label) {
      var upLabelLevelId = []
      for (var i = 0; i < labelTree.length; i++) {
        if (label.labelLevelPathName != null) {
          labelTree[i].labelLevelPathName = label.labelLevelPathName + '-->' + label.labelLevelName
        } else {
          labelTree[i].labelLevelPathName = label.labelLevelName
        }
        if (upLabelLevelId.indexOf(labelTree[i].upLabelLevelId) == -1) {
          upLabelLevelId.push(labelTree[i].upLabelLevelId)
          this.options.push(labelTree[i])
        }
        this.getOptions(labelTree[i].children, labelTree[i])
      }
    },
    getDialogOptions(labelTree, label) {
      for (var i = 0; i < labelTree.length; i++) {
        labelTree[i].labelLevelPathNameDialog = label.labelLevelPathNameDialog + '-->' + labelTree[i].labelLevelName
        this.dialogOptions.push(labelTree[i])
        this.getDialogOptions(labelTree[i].children, labelTree[i])
      }
    },
    handleNodeClick(data) {
      this.params.labelLevelId = data.labelLevelId
      this.page = this.pageInit
      this.page.currentPage = 1
      this.page.offset = 1
      this.getLabelData()
    },
    editStatus(labelId, status) {
      var confLog = ''
      if (status == 1000) {
        confLog = this.$t('labelSpec.tip.onlineTip')
      } else if (status == 1600) {
        confLog = this.$t('labelSpec.tip.offlineTip')
      } else {
        confLog = this.$t('labelSpec.tip.deletedTip')
      }
      this.$confirm(confLog, this.$t('tip'), {
			  confirmButtonText: this.$t('submitText'),
			  cancelButtonText: this.$t('cancelText'),
			  type: 'warning'
      }).then(() => {
        const that = this
        that.loading = true
        this.reqParams.labelId = labelId
        this.reqParams.statusCd = status
        this.R.forTaglib.postJson('/mktlabel/editLabelStatus', this.reqParams).then(res => {
          if (res.ok) {
					   this.$message.success(this.$t('operateSuccess'))
					   this.getLabelData()
          }
        }).catch(err => {
          that.$message.error(err.toString())
        })
        that.loading = false
      })
    },
    refreshChange() {
      this.getLabelData()
    },
    onAddSuccess(isSuccess) {
      console.log(isSuccess)
		    if (isSuccess) {
		        this.getLabelData()
		        this.showAddModel = false
		    }
    },
    onDetailSuccess(isSuccess) {
		    if (isSuccess) {
		        this.getLabelData()
		        this.showDetailModel = false
		    }
    }
  }
}
</script>

<style>
	.el-tree-node>.el-tree-node_children {
	    overflow: visible;
	}
</style>
